<template>
  <div class="main">
    <div class="inner">
      <div class="title">
        <h1 class="fs-28">{{ $t('ismsg.IDO.title') }}</h1>
        <p class="fs-12">{{ $t('ismsg.IDO.subtitle') }}</p>
      </div>
      <div class="cont">
        <p class="text fs-14">{{ $t('ismsg.IDO.text') }}</p>
        <el-row class="actions">
          <el-col :span="12">
            <div :class="{ bnb: activeCoin == 'BNB' }" class="action" @click="changeCoin('BNB')">
              <img src="@/assets/images/BNB.png" alt="" />
              <span class="fs-12">BNB</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div :class="{ usdt: activeCoin == 'USDT' }" class="action" @click="changeCoin('USDT')">
              <img src="@/assets/images/USDT.png" alt="" />
              <span class="fs-12">USDT</span>
            </div>
          </el-col>
        </el-row>
        <div class="exchange fs-12">
          1$AXIE = {{ formatNumber(price, 8) }} <span>{{ activeCoin }}</span>
        </div>
        <el-row class="actions">
          <el-col :span="12">
            <div class="money fs-12">
              <p>{{ activeCoin }} {{ $t('ismsg.IDO.pay') }}</p>
              <div class="val input"><input type="number" maxlength="9" min="1" v-model="inputVal" /></div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="money fs-12">
              <p>{{ $t('ismsg.IDO.get') }}</p>
              <div class="val">{{ receiveAxieAmount }}</div>
            </div>
          </el-col>
        </el-row>
        <div class="line"></div>
        <div class="texttext">{{ $t('ismsg.IDO.purchase') }} </div>
        <el-row class="btnGroups">
          <el-col :md="12" :xs="24">
            <div class="agree fs-14" @click="doIdoBNB" v-if="activeCoin == 'BNB'">
              <img src="@/assets/images/wallet.png" alt="" />
              <span>{{ $t('ismsg.IDO.btns.agree') }} </span>
              <i class="iconfont icon-jiantou_youshang_o"></i>
            </div>
            <template v-if="activeCoin == 'USDT'">
              <div class="agree fs-14" @click="doIdoUsdt" v-if="isApprove">
                <img src="@/assets/images/wallet.png" alt="" />
                <span>{{ $t('ismsg.IDO.btns.agree') }} </span>
                <i class="iconfont icon-jiantou_youshang_o"></i>
              </div>
              <div class="agree fs-14" @click="toApprove" v-else>
                <img src="@/assets/images/wallet.png" alt="" />
                <span>Approve USDT</span>
                <i class="iconfont icon-jiantou_youshang_o"></i>
              </div>
            </template>
          </el-col>
          <el-col :md="12" :xs="24">
            <div class="receive fs-14" @click="showDialog = true">
              <i class="iconfont icon-liwu gift"></i>
              <span> {{ $t('ismsg.IDO.btns.recive') }}<i class="iconfont icon-jiantou_youshang_o arrow"></i></span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
  <div :class="{ show: showDialog }" class="pledgeDialog">
    <div class="pledgeDialogInner">
      <div class="title">
        <span>{{ $t('ismsg.IDO.links.title') }}</span>
      </div>
      <p class="subtitle">
        {{ $t('ismsg.IDO.links.text') }}
      </p>
      <div class="address">
        <p>{{ myInviterAddr }}
          <span class="copyBtn" v-if="myInviterAddr" @click="copy(myInviterAddr)">
            <i class="iconfont icon-fuzhi"></i>{{ $t('ismsg.airdrop.copyBtn') }}
          </span>
        </p>
      </div>
      <div class="confirmBtn" @click="showDialog = false">
        <span>{{ $t('ismsg.IDO.links.btn') }}</span>
      </div>
      <span class="clock" @click="showDialog = false">×</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, watchEffect } from 'vue';
import { useMainStore } from '@/store/index';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { formatNumber } from '@/utils/common';
import { util, usdtContract, axieContract, getSigner, getBnbBalance, getUsdtBalance, getAxieBalance } from '@/a-wallet';

const { t: lang } = useI18n();
const mainStore: any = useMainStore();

const activeCoin = ref('BNB');
const axiePrice = ref(0);
const price = ref(0);
const inputVal: any = ref(null);
const receiveAxieAmount: any = ref(null);
const isApprove = ref(true);
const showDialog = ref(false);
const myInviterAddr = ref('');

onMounted(() => {
  watchEffect(async () => {
    if (mainStore.baseData) {
      axiePrice.value = mainStore.baseData.idoInfo.third;
      myInviterAddr.value = `${window.location.origin}?address=${mainStore.walletAccount}`;
      changeCoin(activeCoin.value);
      checkApprove();
    }
  });
});

watch(inputVal, (inputVal_: any) => {
  if (inputVal_) {
    receiveAxieAmount.value = Number((inputVal_ / price.value).toFixed(8));
  } else {
    receiveAxieAmount.value = null;
  }
});

async function changeCoin(coin: string) {
  activeCoin.value = coin;
  inputVal.value = null;
  if (activeCoin.value == 'BNB') {
    price.value = axiePrice.value / mainStore.baseData.bnbUsdtRatio;
    isApprove.value = true;
  } else {
    price.value = axiePrice.value;
  }
}

/**ido用BNB私募 */
async function doIdoBNB() {
  if (mainStore.loading) return;
  if (!inputVal.value) return;
  const { walletAccount, baseData }: any = mainStore;

  if (inputVal.value * baseData.bnbUsdtRatio < baseData.idoWorthMin) return ElMessage(lang('ismsg.tips.idoWorthMin'));

  const cnt = receiveAxieAmount.value;
  const cntCan = baseData.idoInfo.second - baseData.idoInfo.fourd;
  if (cnt > cntCan) return ElMessage(lang('ismsg.tips.idoRemainNotEnough'));

  const bnbBalance = await getBnbBalance(walletAccount);
  const gas = (baseData.gasPriceAxie1 * baseData.gasLimitAxie1) / 1e18;
  if (bnbBalance < inputVal.value + gas) return ElMessage(lang('ismsg.tips.amountNotEnoughBnb'));

  mainStore.setLoading(true);
  try {
    const extraStr = cnt.toFixed(4);
    let extra = '0x';
    for (let i = 0; i < extraStr.length; i++) {
      extra += extraStr.charCodeAt(i).toString(16);
    }

    const tx = await getSigner().sendTransaction({
      to: baseData.idoAddress,
      value: util.parseEther(inputVal.value.toFixed(6)),
      data: extra
    });

    await tx.wait();
    mainStore.setLoading(false);
    inputVal.value = null;
    ElMessage.success(lang('ismsg.tips.idoSuccess'));
  } catch (error) {
    mainStore.setLoading(false);
    console.error('Error sending transaction:', error);
  }
}

/**ido用USDT私募 */
async function doIdoUsdt() {
  if (mainStore.loading) return;
  if (!inputVal.value) return;
  const { walletAccount, baseData }: any = mainStore;

  if (inputVal.value < baseData.idoWorthMin) return ElMessage(lang('ismsg.tips.idoWorthMin'));

  const cnt = receiveAxieAmount.value;
  const cntCan = baseData.idoInfo.second - baseData.idoInfo.fourd;
  if (cnt > cntCan) return ElMessage(lang('ismsg.tips.idoRemainNotEnough'));

  const usdtBalance = await getUsdtBalance(usdtContract(baseData.contractUsdt), walletAccount);
  const gas = (baseData.gasPriceAxie1 * baseData.gasLimitAxie1) / 1e18;
  if (usdtBalance < inputVal.value + gas) return ElMessage(lang('ismsg.tips.amountNotEnoughUsdt'));

  mainStore.setLoading(true);
  try {
    const tx = await usdtContract(baseData.contractUsdt)
      .connect(getSigner())
      .transfer(baseData.idoAddress, util.parseUnits(inputVal.value.toString()), {
        gasLimit: baseData.gasLimitAxie1,
        gasPrice: baseData.gasPriceAxie1.toString()
      });
    await tx.wait();
    mainStore.setLoading(false);
    inputVal.value = null;
    ElMessage.success(lang('ismsg.tips.idoSuccess'));
  } catch (error) {
    mainStore.setLoading(false);
    console.error('Error sending transaction:', error);
  }
}

/**检查授权 */
async function checkApprove() {
  const { walletAccount, baseData }: any = mainStore;
  const usdtBalance = await getUsdtBalance(usdtContract(baseData.contractUsdt), walletAccount);
  const res = await axieContract(baseData.axieContractAddress).allowance(walletAccount, baseData.axieContractAddress);
  isApprove.value = Number(res) > usdtBalance;
}

/**授权 */
async function toApprove() {
  if (mainStore.loading) return;
  mainStore.setLoading(true);
  try {
    const tx = await axieContract(mainStore.baseData.axieContractAddress)
      .connect(getSigner())
      .approve(mainStore.baseData.axieContractAddress, util.parseUnits((1e10).toString()));
    await tx.wait();
    mainStore.setLoading(false);
    isApprove.value = true;
    ElMessage.success(lang('ismsg.tips.approveSuccess'));
  } catch (error) {
    mainStore.setLoading(false);
    console.error(error);
  }
}
const copy = (val: string) => {
  const input = document.createElement('input'); //创建input
  input.setAttribute('value', val); //把input设置value
  document.body.appendChild(input); //添加这个dom对象
  input.select(); //选中该输入框
  document.execCommand('copy'); //复制该文本
  document.body.removeChild(input); //移除输入框
  ElMessage.success(lang('ismsg.tips.copy'));
};
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  overflow: hidden;
  background-color: rgb(58, 30, 16);

  .divider {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: -5px;
    z-index: 5;

    img {
      width: 100%;
    }
  }

  .cardBox {
    width: 100%;
    max-width: 1550px;
    margin: 0 auto;
    position: relative;
    left: 0;
    bottom: -6vh;
    z-index: 3;

    img {
      width: 100%;
    }
  }
}

.texttext {
  margin-top: 10px;
  font-size: 16px;
  text-align: center;
  font-family: MFBanHei_Noncommercial-Regular;
  background-image: linear-gradient(to bottom, #f99b36, #f35845);
  -webkit-background-clip: text;
  color: transparent;
}

.inner {
  width: 80%;
  padding: 5% 3%;
  margin: 0 auto;
  box-sizing: border-box;
  background: url('@/assets/images/whiteBg.png') no-repeat left top;
  background-size: 100% 100%;
  position: relative;
  z-index: 9;

  .title {
    border-bottom: thin solid rgba($color: #030000, $alpha: 0.15);

    h1 {
      font-size: 38px;
      text-align: center;
      font-family: MFBanHei_Noncommercial-Regular;
      background-image: linear-gradient(to bottom, #f99b36, #f35845);
      -webkit-background-clip: text;
      color: transparent;
    }

    p {
      font-size: 20px;
      color: #572815;
      text-align: center;
      margin: 1vh 0;
      font-weight: 600;
    }
  }

  @mixin btn {
    width: 300px;
    padding: 1.5vh 0;
    display: flex;
    align-items: center;
    border-radius: 8px;
    cursor: pointer;
  }

  .cont {
    width: 90%;
    margin: 0 auto;

    .text {
      color: #572815;
      font-size: 28px;
      text-align: center;
      margin: 1.5vh 0;
      font-weight: 600;
    }

    .actions {
      .action {
        margin: 0 auto 2vh;
        justify-content: center;
        background-color: #fff;
        @include btn();

        span {
          color: #572815;
          font-size: 26px;
          margin-left: 1vw;
          font-weight: 600;
        }

        &.bnb {
          box-shadow: 0px 3px 8px 0px rgba(243, 186, 47, 0.66);
        }

        &.usdt {
          box-shadow: 0px 3px 8px 0px rgba(112, 193, 171, 0.66);
        }
      }
    }

    .exchange {
      width: 50%;
      color: #572815;
      font-size: 20px;
      font-weight: 600;
      margin: 0 auto;
      padding-bottom: 2vh;
      text-align: center;
      border-bottom: thin solid rgba($color: #030000, $alpha: 0.15);
    }

    .money {
      margin: 4vh auto 0;
      width: 300px;

      p {
        color: #572815;
        font-size: 20px;
        margin-bottom: 1vh;
        padding-left: 2vw;
        width: 100%;
        font-weight: 600;
      }

      .val {
        @include btn();
        width: 100%;
        // padding: 1.5vh 2vw;
        height: 46px;
        line-height: 46px;
        padding: 0 2vw;
        margin: 0 auto;
        background-color: #ffffff;
        position: relative;

        input {
          width: 100%;
          border: none;
        }

        &.input {

          // 遮盖计步器
          &::after {
            content: '';
            width: 30px;
            height: 100%;
            display: inline-block;
            background: #ffffff;
            position: absolute;
            top: 0;
            right: 2vw;
            z-index: 3;
          }
        }
      }
    }

    .line {
      width: 50%;
      height: 1px;
      margin: 3vh auto 0;
      border-bottom: thin solid rgba($color: #030000, $alpha: 0.15);
    }

    .btnGroups {
      display: flex;
      justify-content: center;
      flex-wrap: wrap;
      margin: 4vh 0;

      .agree {
        margin: 0 auto;
        background-color: #ffffff;
        justify-content: center;
        color: #572815;
        font-weight: 600;
        @include btn();
        width: 320px;

        span {
          font-size: 22px;
          padding: 0 0.7vw;
          font-family: MFBanHei_Noncommercial-Regular;
        }

        i {
          font-size: 28px;
          position: relative;
          top: 3px;
        }
      }

      .receive {
        margin: 0 auto;
        background-color: #fab30a;
        justify-content: center;
        color: #ffffff;
        font-weight: 600;
        @include btn();
        width: 320px;

        span {
          font-size: 22px;
          padding: 0 0.7vw;
          font-family: MFBanHei_Noncommercial-Regular;
        }

        i {
          font-size: 28px;
        }

        .arrow {
          position: relative;
          top: 3px;
        }
      }
    }
  }
}

.pledgeDialog {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -9;
  width: 100vw;
  height: 100vh;
  opacity: 0;
  background-color: rgba(0, 0, 0, 0.4);
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;

  &.show {
    z-index: 100;
    opacity: 1;
    transition: all 0.3s;
  }

  .pledgeDialogInner {
    max-width: 600px !important;
    width: 80%;
    padding: 20px;
    background-color: #fff;
    border-radius: 12px;
    position: relative;

    .title {
      font-size: 22px;
      font-weight: 700;
      text-align: center;
      line-height: 40px;
      font-family: MFBanHei_Noncommercial-Regular;
      background-image: linear-gradient(to bottom, #f99b36, #f35845);
      -webkit-background-clip: text;
      color: transparent;
    }

    .subtitle {
      color: #5a2a16;
      font-size: 16px;
      text-align: center;
      margin: 1vh 0;

      span {
        color: #e65d40;
      }
    }

    .address {
      width: 90%;
      margin: 0 auto;
      padding: 5px 15px;
      border-radius: 20px;
      font-family: ArialMT;
      font-size: 14px;
      color: #572815;
      border: thin solid rgba(116, 55, 46, 0.09);
      background-color: #ffffff;
      min-height: 33px;

      p {
        word-break: break-all;
      }

      .copyBtn {
        margin-left: 8px;
        color: #41b2f5;
        font-size: 16px;
        cursor: pointer;
        -webkit-tap-highlight-color: transparent;

        i {
          margin-right: 5px;
        }
      }
    }

    .confirmBtn {
      text-align: center;
      margin-top: 2vh;

      span {
        display: inline-block;
        padding: 10px 20px;
        background-color: #6cae86;
        border-radius: 20px;
        color: #fff;
        overflow: hidden;
        cursor: pointer;
      }
    }

    .clock {
      position: absolute;
      top: -9px;
      right: -9px;
      z-index: 100;
      display: inline-block;
      width: 20px;
      line-height: 20px;
      background-color: #fff;
      border: 1px solid #f6a526;
      border-radius: 50%;
      color: #f6a526;
      font-size: 22px;
      text-align: center;
      cursor: pointer;
    }
  }
}

@media screen and (max-width: 992px) {
  .btnGroups {
    .receive {
      margin-top: 1.5vh !important;
    }
  }
}

@media screen and (max-width: 768px) {
  .texttext {
    font-size: 12px;
    margin-top: 5px;
  }

  .inner {
    width: 90%;
    padding: 8% 3%;
    border-radius: 20px;
    overflow: hidden;

    .title {
      h1 {
        font-size: 32px;
        background-image: linear-gradient(to bottom, #f99b36 10%, #f35845 45%, #f99b36 52%, #f35845 100%);
        -webkit-background-clip: text;
        color: transparent;
      }

      p {
        font-size: 18px;
      }
    }

    .cont {
      width: 100%;

      .text {
        font-size: 24px;
      }

      .actions {
        .action {
          padding: 1vh 0 !important;
          width: 120px !important;
          -webkit-tap-highlight-color: transparent;

          img {
            width: 26px;
          }

          span {
            font-size: 16px !important;
          }
        }

        .money {
          width: 130px !important;

          p {
            font-size: 16px !important;
            padding-left: 0;
            text-align: center;
          }

          .val {
            -webkit-tap-highlight-color: transparent;
          }
        }
      }
    }

    .btnGroups {
      margin: 2vh 0 !important;

      .agree,
      .receive {
        width: 100% !important;

        span {
          font-size: 16px !important;
        }

        i {
          font-size: 20px !important;
        }
      }
    }
  }
}

@media screen and (max-width: 500px) {
  .money .val {
    padding-left: 5vw;
  }

  .line {
    width: 80% !important;
    margin: 1vh auto 0 !important;
  }

  .exchange {
    width: 80% !important;
  }

  .money {
    margin-top: 2vh !important;

    .val {
      padding-left: 20px !important;
    }

    .input::after {
      display: none !important;
    }
  }
}
</style>
